package edu.hit.pact.pgse.crawler.finish;

import java.util.Date;

import org.apache.commons.logging.Log;

import edu.hit.pact.pgse.bean.TaskPieceProperty;
import edu.hit.pact.pgse.util.Globals;

public class FinishChecker {
	public static boolean isFinish(Log logger, TaskPieceProperty taskPieceProperty){

		if (taskPieceProperty == null) {
			logger.error("finish because fetch task piece property is null!! There must be something wrong!!");
			return true;
		}// end if
		
		if (taskPieceProperty.getStatus() != TaskPieceProperty.ALIVE) {
			logger.error("finish because pieceProperty status is not alive");
			return true;
		}//end if
		
		if (taskPieceProperty.getSucceededPageNum() >= taskPieceProperty.getPiece().getMaxPageNum()) {
			logger.error("finish because its succeededPageNum "+taskPieceProperty.getSucceededPageNum() +" larger than maxPageNum "+ taskPieceProperty.getPiece().getMaxPageNum());
			taskPieceProperty.setStatus(TaskPieceProperty.FINISHED);
			return true;
		}
		
		if ((taskPieceProperty.getCleanUrlQueue().size() == 0 && taskPieceProperty.getSemaphore() ==0)) {
			logger.error("finish because cleanQueue are both 0    "+ taskPieceProperty.getSemaphore());
			taskPieceProperty.setStatus(TaskPieceProperty.FINISHED);
			return true;
		} 
		
		long nowTime = (new Date()).getTime();
		long startTime = taskPieceProperty.getStartTime();
		if (nowTime - startTime > Globals.CRAWLER_FINISH_CHECK_WAITTING_MILLISECONDS){//10 minutes, 10*60*1000
			logger.error("finish because task piece time expired. began at " + startTime + " , end at " + nowTime);
			taskPieceProperty.setStatus(TaskPieceProperty.FINISHED);
			return true;
		}
		
		return false;
	}
}
